import axios from 'axios'
import { getToken } from './auth'
import router from '../router'

// 创建 axios 实例
const service = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = getToken()
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code !== 1) {
      // 处理业务错误
      if (res.code === 401) {
        // token 过期或无效
        removeToken()
        router.push('/login')
      }
      return Promise.reject(new Error(res.message || '未知错误'))
    }
    return res
  },
  error => {
    console.error('请求失败:', error)
    return Promise.reject(error)
  }
)

export default service